#!/usr/bin/env python3

# Render sample code with all Pygments styles
# Print it to stdout
#
# If the file __file__.css (pygsgallery.py.css) exists,
# its content will be prepended to the result, in <style> tags 

import re
from pygments import __version__,highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import CssLexer,PythonLexer
from pygments.styles import get_all_styles
from sys import stderr

def print_err(*args, **kwargs):
    print(*args, file=stderr, **kwargs)

def complementaryColor(my_hex):
   """Returns complementary RGB color
   Example:
   >>>complementaryColor('FFFFFF')
   '000000'
   """
   rgb = (my_hex[0:2], my_hex[2:4], my_hex[4:6])
   comp = ['%02X' % (255 - int(a, 16)) for a in rgb]
   return ''.join(comp)

raw_code_css = """a:hover {
\tbackground: url("https://x.co/1.jpg");
\ttransform: skew(-8deg) translate(0,0);
}"""

raw_code_py = """#!/usr/bin/python
from sys import __version__,path
def get_syntax():
\tlx = ed.get_prop(CARET)
\tif lx in lexers:
\t\tprint('V: %s' % sys.__version__)"""

out='<div class="all">'
toc='<input id="dd" type="checkbox"/><label class=boxed for="dd">TOC</label><div class="boxed ddc">'
post='</div>'+'<p>Pygments version: '+__version__+'</p>'

count=0
for style in sorted(list(get_all_styles())): # one <div> with header & code block for each style
   count+=1
   print_err("Processing style "+style)

   f_html = HtmlFormatter(nowrap=True,style=style,noclasses=True)
   css=f_html.get_style_defs('.' + style)
   bg_only=re.findall('\n\.'+style+' +\{ *background: *#(......); *}',css) # find a rule that defines default background only, but not foreground?
   if bg_only: # If yes, we add the foreground as a complementary color of the background:
      comp=complementaryColor(bg_only[0])
      css=re.sub('\n\.'+style+' +\{ *background: *#'+bg_only[0]+'; *}','\n.'+style+' { background: #'+bg_only[0]+'; color: #'+comp+' /*gen*/ }',css,1)
   bg=re.findall('\n\.'+style+' +\{ *background: *#(......); color: *#......;?',css) # finding the default background
   fg=re.findall('\n\.'+style+' +\{ *background: *#......; color: *#(......);?',css) # finding the default color

   css=css.splitlines(keepends=True)[6] # just 1 line from the style's css
   css=css.replace("; color:",";\n\tcolor:")
   css=css.replace("{ background:","{\n\tbackground:")
   css=css.replace(" }","\n}")
   css='/* Just some CSS */\n'+css+raw_code_css
   code=highlight(css,CssLexer(),f_html)+highlight(raw_code_py,PythonLexer(),f_html)

   out=out+'<div><h2 id="%s-%03d">%s (%03d)<a href="#"></a></h2>' % (style,count,style,count)
   toc=toc+'<a href="#%s-%03d">%s (%03d)</a>' % (style,count,style,count)
   out=out+'<pre style="background:#'+bg[0]+';color:#'+fg[0]+'">'+code+'</pre></div>' # closing <div class="w"> 

toc=toc+'</div>'
out=toc+out+post

with open(__file__+'.css',mode='r',encoding="utf-8") as f:
    css=f.read();
    out='<style>'+css+'</style>'+out

try:
    # not strictly necessary, but saves a few %
    # pip install minify-html
    import minify_html
    print_err("Minifying output... ")
    print(minify_html.minify(out,minify_css=True,remove_bangs=True,remove_processing_instructions=True))
except:
    print(out)
